package com.ehotting.edsta.diagnosisPredict.utils;

import feign.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Collection;

@Slf4j
public class CommonUtils {

    public static void downloadFileFromFeign(HttpServletResponse response, String filename, Response feignResponse) {
        InputStream inputStream = null;
        BufferedInputStream bufferedInputStream = null;
        OutputStream outputStream = null;
        try {
            response.reset();

            // 设置ContentType，响应内容为二进制数据流，编码为utf-8，此处设定的编码是文件内容的编码
            response.setContentType("application/octet-stream;charset=utf-8");
            // 以（Content-Disposition: attachment; filename="filename.jpg"）格式设定默认文件名，设定utf编码，此处的编码是文件名的编码，使能正确显示中文文件名
            Collection<String> contentDisposition = feignResponse.headers().get("Content-Disposition");
            String contentDispositionVal = "attachment;fileName=" + filename + ";filename*=utf-8''" + URLEncoder.encode(filename, "utf-8");
            if (!CollectionUtils.isEmpty(contentDisposition)){
                contentDispositionVal = contentDisposition.toArray()[0].toString();
            }
            response.setHeader("Content-Disposition", contentDispositionVal);
            inputStream = feignResponse.body().asInputStream();
            //使用这个buffereInputStream 为了防止大文件内存溢出
            bufferedInputStream = new BufferedInputStream(inputStream);
            outputStream = response.getOutputStream();
            //每次取出5M
            byte[] buffer = new byte[1024 * 1024];
            int len;
            while ((len = bufferedInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
        } catch (Exception e) {
            log.error("下载文件异常：", e);
        } finally {
            try {
                if (inputStream!=null){
                    inputStream.close();
                }
                if (outputStream!=null){
                    outputStream.close();
                }
                if (bufferedInputStream!=null){
                    bufferedInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
